package com.bonc.classifier.maxent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import com.bonc.utilities.EventUtility;
import com.bonc.vectorspace.model.EventCorpus;
import com.bonc.vectorspace.model.EventDocument;
import com.bonc.vectorspace.model.VectorSpaceModel;

import cc.mallet.classify.Classifier;
import cc.mallet.types.Alphabet;
import cc.mallet.types.FeatureVector;
import cc.mallet.types.Instance;
import cc.mallet.types.Label;
import cc.mallet.types.LabelAlphabet;
import cc.mallet.types.Labeling;

/**
 * @author donggui@bonc.com.cn
 * @version 2016 2016年6月28日 下午5:00:38
 */
public class EventClassifier {
	
	public static double  ClassifyThreshold = 0.60;
	

	public static List<String> predictEvent(Classifier classifier,Set<String> featureTerms, List<EventDocument> documents){
		List<String> targetValues  = new ArrayList<String>();
		//		if(content !=null && !"".equals(content.trim())){
		//convert content to instances
		//			List<EventDocument> documents = EventUtility.convertText2Document(content.trim(),null);

		//classify,predict
		if(documents!=null && documents.size()>0){

			Alphabet featureAlphabet =classifier.getAlphabet();//特征词典
			LabelAlphabet targetAlphabet = classifier.getLabelAlphabet();//类标词典

			//InstanceList instances = new InstanceList (featureAlphabet,targetAlphabet);//实例集对象

			EventCorpus corpus = new EventCorpus(documents);
			VectorSpaceModel vectorSpace = new VectorSpaceModel(corpus,featureTerms);		
			//			int row = documents.size();
			int featuresize = featureTerms.size();

			for (EventDocument document : corpus.getDocuments()) {
				System.out.println("document "+(document.getDocId()+"===="+document.getContent()));
				HashMap<String, Double> weights = vectorSpace.getTfIdfWeights().get(document);
				double[] featureValues1 = new double[featuresize];
				int j = 0;
				for (String term : featureTerms) {				
					Double weight = weights.get(term);
					if(weight !=null ){
						featureValues1[j] = weight.doubleValue();
					}else{
						featureValues1[j] = 0.0;
					}
					j++;				
				}

				FeatureVector featureVector = new FeatureVector(featureAlphabet,featureTerms.toArray(new String[featuresize]),featureValues1);//change list to array

				Instance testInstance = new Instance (featureVector,null, document.getDocId(),null);
				Labeling labeling = classifier.classify(testInstance).getLabeling();
				Label bestLabel = labeling.getBestLabel();
				double bestValue = labeling.getBestValue();
				if("pos" == (String)bestLabel.getEntry() && bestValue >= EventClassifier.ClassifyThreshold){
					targetValues.add((String)bestLabel.getEntry());
					System.out.println(labeling.toString());
					//		        	System.out.println((String)bestLabel.getEntry() + ':'+bestLabel.getBestValue());
				}else{
					targetValues.add("neg");
				}
			}		
		}


		return targetValues;
	}

}
